import sys
sys.path.append("..")
import CloudStack
from time import gmtime, strftime
import time
from Api_connect import Api_connect


class Cloudstack_option:
    def __init__(self):
        api=Api_connect('api.conf')
        self.api_server='http://'+api.get_server()+':8080/client/api'
        #print self.api_server
        self.api_key = api.get_api_key()
        #print self.api_key
        self.secret_key = api.get_sec_Key()
        #print self.secret_key
        self.cloudstack = CloudStack.Client(self.api_server, self.api_key, self.secret_key)
        #print self.cloudstack
        
    def get_all_template(self):
        args={'templatefilter':'self'}
        template_list=self.cloudstack.listTemplates(args)
        return template_list
    
    def get_template(self,args_value):
        args={'templatefilter':'self'}
        args.update(args_value)
        template_info={}
        template=self.cloudstack.listTemplates(args)
        template_id=template[0]['id']
        template_info.update({'id':template_id})
        template_status=template[0]['status']
        template_info.update({'status':template_status})
        template_name=template[0]['name']
        template_info.update({'name':template_name})
        template_ostypeid=template[0]['ostypeid']
        template_info.update({'ostypeid':template_ostypeid})
        return template_info 
        
    def get_all_instance(self,account):
        args={}
        if account == "":
            args={"listall":"true"}
        elif account != "":
            args={"account":account}
        else:
            args=""
        instances=self.cloudstack.listVirtualMachines(args)
        return instances
    
    def get_all_account(self):
        instances=self.cloudstack.listAccounts({"listall":"true"})
        return instances
   
    def get_instance(self,args_value):
        args={}
        args.update(args_value)
        instance_info={} 
        instances=self.cloudstack.listVirtualMachines(args)
        instance_id=instances[0]['id']
        instance_info.update({'id':instance_id})
        instance_ip=instances[0]['nic'][0]['ipaddress']
        instance_info.update({'ipaddress':instance_ip})
        instance_tep=instances[0]['templateid']
        instance_info.update({'templateid':instance_tep})
        instance_status=instances[0]['state']
        instance_info.update({'status':instance_status})
        instance_name=instances[0]['name']
        instance_info.update({'name':instance_name})
        instance_offeringid=instances[0]['serviceofferingid']
        instance_info.update({'serviceofferingid':instance_offeringid})
        instance_guestosid=instances[0]['guestosid']
        instance_info.update({'guestosid':instance_guestosid})
        instance_rootdeviceid=instances[0]['rootdeviceid']
        instance_info.update({'rootdeviceid':instance_rootdeviceid})
        return instance_info  
        
    def delete_template(self,args_value):
        args={"id":args_value}
        job=self.cloudstack.deleteTemplate(args)
        return job
        
        
    def delete_instance(self,args_value):
        args={"id":args_value}
        job=self.cloudstack.destroyVirtualMachine(args)
        return job

    def deploy_instance(self,args={}):
        if not "serviceofferingid" in args or not "templateid" in args or not "zoneid" in args:
            print "args need 'serviceofferingid,templateid and zoneid'"
            return
        if args['name'] != "":
            instances=self.get_all_instance("")
            for i in range(len(instances)):
                if args['name'] == instances[i]["name"]:
                    print instances[i]["name"]
                    return "don't created , the host name have been used"
        req=self.cloudstack.deployVirtualMachine(args)
        return req
    
    def list_volume(self):
        volumes=self.cloudstack.listVolumes()
        return volumes
    
    def get_volume(self,instance_info):
        args={}
        instance_id=instance_info['id']
        args.update({'virtualmachineid':instance_id})
        volume=self.cloudstack.listVolumes(args)
        return volume
    
    def check_job(self,job_id):
        jobs = self.cloudstack.listAsyncJobs()
        for job in jobs:
            if job['jobid'] == job_id:
                return job['jobstatus']
        
    def get_zone(self,id):
        req = self.cloudstack.listZones({"id":id})
        return req
        
    def create_template(self,instance_info):
        args={}
        volume_info=self.get_volume(instance_info)
        volue_id=volume_info[0]['id']
        start_time= strftime("%Y%m%d%H%M%S", gmtime())
        displaytext=instance_info['name']+"-"+start_time
        ostype_id=instance_info['guestosid']
        # print instance_info['status']
        if instance_info['status'] != "Stopped":
            req=self.cloudstack.stopVirtualMachine({'id':instance_info['id']})
            job_id=req['jobid']
            job_req = 0
            while job_req != 1 :
                time.sleep(10)
                job_req=self.check_job(job_id)
            
        args.update("")
        args.update({'displaytext':displaytext})
        args.update({'name':displaytext})
        args.update({'ostypeid':ostype_id})
        args.update({'volumeid':volue_id})
        #print args
        if not "displaytext" in args or not "name" in args or not "ostypeid" in args:
            print "args need 'displaytext,name and ostypeid'"
            return
        req=self.cloudstack.createTemplate(args)
        job_id=req['jobid']
        job_req = 0
        while job_req != 1 :
            time.sleep(5)
            job_req=self.check_job(job_id)
            if job_req == 1:
                req=self.cloudstack.startVirtualMachine({'id':instance_info['id']})
                
        return req

#class CreateTemplate(threading.Thread):
#    def __init__(self,args,cs):
#        threading.Thread.__init__(self)
#       self.args=args
#        self.cs=cs
#       #self.start()
#    def run(self):
#        instance_info=self.cs.get_instance(self.args)
#        jobs=self.cs.create_template(instance_info)
#        print jobs
#            
#    def stop(self):
#        self.thread_stop = True
def main():
    cs=Cloudstack_option()
    print cs.get_all_instance("")
#    threads=[]
#    args={"name":"web02",}
#    ths=CreateTemplate(cs,args)
#    print ths
    #inargs={"zoneid":"fc42e7aa-8167-40a7-b84c-ebffd5961203",
    #        "templateid":template_id,
    #       "name":'web04'}
    #cs.deploy_instance(inargs)
    
    
    #args={"name":"lvs-web"}
    #tp=cs.get_template(args)
    #print tp
    #job=cs.delete_template('df597dac-ab6f-47f6-99c6-7084c72485dd')
    #print job
     

if __name__ == "__main__":
    main()




#for vm in vms:
#     print "%s" % (vm['id'])
     
     
#vms= cloudstack.deployVirtualMachine({'templateid':'aacb8b38-5fd9-4844-86ca-5812565ffe7a',
#                                      'zoneid':'1',
#                                      'serviceofferingid':'27400a20-c914-44bc-8a14-8b799e5b0080',
#                                      'name':'est'})

